package com.Babysleep.Interface;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import com.Babysleep.R;
import com.Babysleep.Activity.MaMaShuo;
import com.Babysleep.manage.Constant;

/**
 * 控制计数器。
 * 
 */
public class Count_Handler extends Handler {

	boolean need_send = false;
	TextView counter;
	long start_time = 0;
	long pause_time = 0;
	boolean is_paused = false;
	long last_length = 0;
	Activity activity;

	public Count_Handler(Activity activity) {
		this.activity = activity;
	}

	/*
	 * (non-Javadoc) 重写handleMessage方法，case1为妈妈说录音
	 */
	@Override
	public void handleMessage(Message msg) {
		// TODO Auto-generated method stub
		super.handleMessage(msg);
		switch (msg.what) {
		case 0:
			if (need_send) {
				UI();
				sendEmptyMessageDelayed(1, 1000);
			}
			break;
		// 当录音时长大于十分钟，自动停止。
		case 1:
			if (need_send) {
				UI();

				if ((System.currentTimeMillis() - start_time) >= Constant.length) {
					new MaMaShuo().start_record();
					need_send = false;
				}

				sendEmptyMessageDelayed(1, 1000);
			}
			break;

		default:
			break;
		}
	}

	public void start() {
		need_send = true;
		start_time = System.currentTimeMillis();
		counter = (TextView) activity.findViewById(R.id.counter);
		sendEmptyMessage(1);
		if (is_paused) {
			is_paused = false;
		}
	}

	public void stop() {
		counter = null;
		need_send = false;
		last_length = 0;
	}

	public void pause() {
		is_paused = true;
		last_length = System.currentTimeMillis() - start_time;
		need_send = false;
	}

	/**
	 * 更改view的text
	 */
	public void UI() {

		SimpleDateFormat df = new SimpleDateFormat("mm:ss");
		df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
		counter.setText(df.format(System.currentTimeMillis() - start_time
				+ last_length));
	}
}
